package com.kaiwukj.android.ufamily.mvp.ui.page.service.repairs;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.blankj.utilcode.util.LogUtils;
import com.kaiwukj.android.mcas.di.component.AppComponent;
import com.kaiwukj.android.ufamily.R;
import com.kaiwukj.android.ufamily.app.base.review.BaseMvpFragment;
import com.kaiwukj.android.ufamily.di.component.DaggerServiceComponent;
import com.kaiwukj.android.ufamily.di.module.ServiceModule;
import com.kaiwukj.android.ufamily.exception.AppException;
import com.kaiwukj.android.ufamily.mvp.helper.GlideEngine;
import com.kaiwukj.android.ufamily.mvp.http.entity.params.PostRepairParams;
import com.kaiwukj.android.ufamily.mvp.http.entity.result.RepairsResult;
import com.kaiwukj.android.ufamily.mvp.http.entity.resultbak.ComplainType;
import com.kaiwukj.android.ufamily.mvp.ui.adapter.TypeAdapter;
import com.kaiwukj.android.ufamily.mvp.ui.adapter.UploadAdapter;
import com.kaiwukj.android.ufamily.mvp.ui.page.service.ServiceContract;
import com.kaiwukj.android.ufamily.mvp.ui.widget.CustomPopupWindow;
import com.kaiwukj.android.ufamily.mvp.ui.widget.home.PopupWindowUtil;
import com.kaiwukj.android.ufamily.utils.AudioRecoderUtils;
import com.kaiwukj.android.ufamily.utils.AudioUtils;
import com.kaiwukj.android.ufamily.utils.FileUtil;
import com.kaiwukj.android.ufamily.utils.LocalMediaUtils;
import com.kaiwukj.android.ufamily.utils.VideoUtils;
import com.kaiwukj.android.ufamily.utils.upload.OnUploadListener;
import com.kaiwukj.android.ufamily.utils.upload.UploadBean;
import com.kaiwukj.android.ufamily.utils.upload.UploadUtils;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.listener.OnResultCallbackListener;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Objects;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

import static com.kaiwukj.android.ufamily.app.constant.ARouterUrlKt.MyHouseUrl;
import static com.kaiwukj.android.ufamily.utils.Utils.runOnUiThread;

/**
 * @author Charles
 * @date 2019/8/14.
 * description：Kaiwu
 */
public class RepairsFragment extends BaseMvpFragment<RepairsPresenter> implements ServiceContract.RepairsView {
    @BindView(R.id.rv_complain_type)
    RecyclerView rvComplainType;
    @BindView(R.id.rv_complain_upload)
    RecyclerView rvComplainUpload;
    @BindView(R.id.ll_root_view)
    ViewGroup llRootView;
    @BindView(R.id.et_content)
    EditText etContent;
    @BindView(R.id.tv_record)
    TextView tvRecord;
    @BindView(R.id.iv_record_delete)
    View ivRecordDelete;
    @BindView(R.id.ll_choose_time)
    LinearLayout llChooseTime;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.tv_house)
    TextView tvHouse;
    @BindView(R.id.rl_to_choose_house)
    ViewGroup containerHouse;

    private static final int REQUEST_CODE_CHOOSE_IMAGE = 1;
    private static final int REQUEST_CODE_CHOOSE_VIDEO = 2;
    private static final int REQUEST_CODE_CHOOSE_HOUSE = 3;
    private static final int MAX_LENGTH = 167772160;

    private String qiNiuToken;
    private List<String> imgs = new ArrayList<>();
    private String videoUrl;
    private String coverUrl;
    private String videoPath;
    private String audioUrl;
    private String audioPath;
    private int typeId = 0;
    private int houseId = 0;
    private boolean haveTime = false;

    private UploadAdapter uploadAdapter;
    private TypeAdapter repairTypeAdapter;
    private AudioRecoderUtils audioRecoderUtils;
    private MediaPlayer mediaPlayer;
    private Timer recordTimer;

    private boolean needHouse = false;

    private mHandle mHandler = new mHandle();

    private List<String> urls = new ArrayList<>();

    @OnClick({R.id.tv_record, R.id.iv_record_delete,
            R.id.btn_commit,
            R.id.rl_to_choose_house, R.id.ll_choose_time})
    void onViewClick(View v) {
        switch (v.getId()) {
            case R.id.tv_record:
                if (mediaPlayer == null) {
                    initPlayer(audioPath);
                } else {
                    if (mediaPlayer.isPlaying()) {
                        mediaPlayer.stop();
                        mediaPlayer = null;
                    } else {
                        initPlayer(audioPath);
                    }
                }

                break;
            case R.id.iv_record_delete:
                audioUrl = "";
                tvRecord.setVisibility(View.GONE);
                ivRecordDelete.setVisibility(View.GONE);
                uploadAdapter.setHaveAudio(false);
                break;
            case R.id.btn_commit:
                if (!TextUtils.isEmpty(coverUrl)) {
                    showLoading();
                    // List<String> coverImgs = new ArrayList<>();
                    // coverImgs.add(coverUrl);
                    uploadType = 1;
                    UploadUtils.getInstance().upload(coverUrl, qiNiuToken, UploadUtils.IMAGE, onUploadListener);
                    // UploadUtils.getInstance().uploadImages(coverImgs, qiNiuToken, onUploadListener);
                } else {
                    commit();
                }
                break;
            case R.id.rl_to_choose_house:
                ARouter.getInstance().build(MyHouseUrl)
                        //.withBoolean("EXTRA_KEY_PICK_HOUSE", true)
                        //.withString("EXTRA_KEY_FRAGMENT", "EXTRA_KEY_HOUSE")
                        .withBoolean("isPick", true)
                        .navigation(getActivity(), REQUEST_CODE_CHOOSE_HOUSE);
                break;
            case R.id.ll_choose_time:
                boolean[] types = new boolean[]{true, true, true, true, true, false};
                Calendar calendarLater = Calendar.getInstance();
                calendarLater.add(Calendar.YEAR, 1);
                TimePickerBuilder timePickerBuilder = new TimePickerBuilder(getActivity(), (date, v2) -> {
                    haveTime = true;
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    tvTime.setText(simpleDateFormat.format(date.getTime()));
                }).setRangDate(Calendar.getInstance(), calendarLater)
                        .setOutSideCancelable(true)
                        .setCancelColor(R.color.common_text_slight_color)
                        .isCyclic(false)
                        .setLineSpacingMultiplier(1.8f)
                        .setSubmitColor(R.color.app_color_theme)
                        .setType(types);
                timePickerBuilder.build().show();
                break;
        }
    }

    public static RepairsFragment newInstance() {
        Bundle args = new Bundle();
        RepairsFragment fragment = new RepairsFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void setupFragmentComponent(@NonNull AppComponent appComponent) {
        DaggerServiceComponent.builder()
                .appComponent(appComponent)
                .serviceModule(new ServiceModule(this))
                .build().inject(this);
    }

    @Override
    protected int getLayoutId() {
        ARouter.getInstance().inject(this);
        return R.layout.fragment_repairs;
    }

    @Override
    protected void initView() {

    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        mPresenter.requestQIToken();
        initRecyclerView();

        tvRecord.getBackground().setLevel(2);
        recordTimer = new Timer();
    }

    private void commit() {
        if (TextUtils.isEmpty(etContent.getText().toString())) {
            showMessage("请填写报修详情");
            return;
        }
        if (typeId == 0) {
            showMessage("请选择报修类型");
            return;
        }
        if (!haveTime) {
            showMessage("请选择预约时间");
            return;
        }
        if (needHouse && houseId == 0) {
            showMessage("请选择报修房屋");
            return;
        }
        submitRequest();
    }

    private void submitRequest() {
        PostRepairParams complainRequest = new PostRepairParams();
        complainRequest.setContent(etContent.getText().toString());
        StringBuilder stringBuffer = new StringBuilder();
        if (imgs.size() > 0) {
            String imglists;
            for (int i = 0; i < imgs.size(); i++) {
                stringBuffer.append(imgs.get(i).trim()).append(",");
            }
            imglists = stringBuffer.substring(0, stringBuffer.length() - 1);
            complainRequest.setImg(imglists);
        }
        complainRequest.setVideo(videoUrl);
        complainRequest.setVoice(audioUrl);
        complainRequest.setCoverUrl(coverUrl);
        complainRequest.setType(typeId);
        complainRequest.setBookingTime(tvTime.getText().toString());
        complainRequest.setRoomId(houseId);
        complainRequest.setCommunityId(getApp().getUserInfo().getLastCommunityId());

        mPresenter.postRepair(complainRequest);
    }

    private void initRecyclerView() {
//        配置投诉类型列表
//        报修类型：1房屋质量、2电梯、3楼梯、4公共设施、5健身器材、6公共照明、7其他
        List<ComplainType> data = new ArrayList<>();
        data.add(new ComplainType(1, "房屋质量"));
        data.add(new ComplainType(2, "电梯"));
        data.add(new ComplainType(3, "楼梯"));
        data.add(new ComplainType(4, "公共设施"));
        data.add(new ComplainType(5, "健身器材"));
        data.add(new ComplainType(6, "公共照明"));
        data.add(new ComplainType(7, "其他"));
        repairTypeAdapter = new TypeAdapter(getContext(), R.layout.item_type, data);
        rvComplainType.setLayoutManager(new GridLayoutManager(getContext(), 3));
        rvComplainType.setAdapter(repairTypeAdapter);
        repairTypeAdapter.setOnSelectedListener(id ->
                {
                    typeId = id;
                    if (typeId == 1) {
                        containerHouse.setVisibility(View.VISIBLE);
                    } else {
                        containerHouse.setVisibility(View.GONE);
                    }
                }
        );
        repairTypeAdapter.check(0);

//        配置上传rv
        uploadAdapter = new UploadAdapter(getContext());
        uploadAdapter.setMaxImgs(3);
        rvComplainUpload.setLayoutManager(new GridLayoutManager(getContext(), 4));
        rvComplainUpload.setAdapter(uploadAdapter);
        uploadAdapter.setOnItemClickListener(new UploadAdapter.onItemClickListener() {
            @Override
            public void onAudioClick() {
                requestAudioPermissions();
            }

            @Override
            public void onVideoClick() {
                requestPermissions(2);
            }

            @Override
            public void onShowVideoClick(String coverUrl) {
                PopupWindowUtil.createVideoPop(getActivity(), videoPath, coverUrl).showCenter(R.layout.fragment_complain);
            }

            @Override
            public void onDeleteVideoClick() {
                uploadAdapter.setVideoUrl("");
                videoUrl = "";
                coverUrl = "";
            }

            @Override
            public void onAddClick() {
                requestPermissions(1);
            }

            @Override
            public void onDelImgClick(int position) {
                uploadAdapter.removeImg(position);
                imgs.remove(position);
            }

            @Override
            public void onImgClick(List<String> imgUrls, int position) {
                PopupWindowUtil.createImageDialog(getActivity(), imgUrls.get(position)).showCenter(R.layout.fragment_complain);
            }
        });
    }

    private void requestPermissions(int type) {
        RxPermissions rxPermission = new RxPermissions(this);
        Disposable disposable = rxPermission
                .requestEach(
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE
                )
                .subscribe(permission -> {
                    if (permission.granted) {
                        // 用户已经同意该权限
                        switch (type) {
                            case 1:
                                PictureSelector.create(this)
                                        .openGallery(PictureMimeType.ofImage())
                                        .isCompress(true)
                                        .compressQuality(75)
                                        .maxSelectNum(3 - imgs.size())
                                        .imageEngine(GlideEngine.createGlideEngine())
                                        .theme(R.style.MyImagePickerStyle)
                                        //.forResult(PictureConfig.CHOOSE_REQUEST);
                                        .forResult(new OnResultCallbackListener<LocalMedia>() {
                                            @Override
                                            public void onResult(List<LocalMedia> result) {
                                                List<String> paths = new ArrayList<>();
                                                for (LocalMedia media : result) {
                                                    if (media.isCompressed()) {
                                                        paths.add(media.getCompressPath());
                                                    } else {
                                                        paths.add(media.getPath());
                                                    }
                                                }
                                                uploadImage(paths);
                                            }

                                            @Override
                                            public void onCancel() {

                                            }
                                        });
                                break;
                            case 2:
                                PictureSelector.create(this)
                                        .openGallery(PictureMimeType.ofVideo())
                                        // .selectionMode(PictureConfig.SINGLE)
                                        .imageEngine(GlideEngine.createGlideEngine())
                                        .videoMaxSecond(15)
                                        .videoMinSecond(3)
                                        .maxSelectNum(1)
                                        .maxVideoSelectNum(1)
                                        .theme(R.style.MyImagePickerStyle)
                                        .forResult(new OnResultCallbackListener<LocalMedia>() {
                                            @Override
                                            public void onResult(List<LocalMedia> result) {
                                                LocalMediaUtils.handlePath(result);
                                                LocalMedia media = result.get(0);
                                                if (media.getMimeType().equals("video/mp4")) {
                                                    //uploadVideo(media.getRealPath());
                                                    subscribe(Observable.create((ObservableOnSubscribe<String>) emitter -> {
                                                        VideoUtils.getInstance().startCompressed(getContext(), result.get(0).getRealPath(), -1, new VideoUtils.OnVideoDealListener() {
                                                            @Override
                                                            public void onSuccess(String filePath) {
                                                                emitter.onNext(filePath);
                                                            }

                                                            @Override
                                                            public void onFailed(int errorCode, String errorMsg) {
                                                                // showMessage(errorCode + ":" + errorMsg);
                                                                emitter.onError(new AppException(errorCode, errorMsg));
                                                            }

                                                            @Override
                                                            public void onProgressUpdate(float progress) {
                                                            }
                                                        });
                                                    })
                                                            .doOnSubscribe(act -> showLoading("正在处理..."))
                                                            .doFinally(() -> hideLoading())
                                                            .subscribeOn(Schedulers.computation())
                                                            .observeOn(AndroidSchedulers.mainThread())
                                                            .subscribe(result1 -> {
                                                                uploadVideo(result1);
                                                            }, error -> {
                                                                if (error instanceof AppException) {
                                                                    if (((AppException) error).getErrCode() == 8 || ((AppException) error).getErrCode() == 9) {
                                                                        uploadVideo(result.get(0).getRealPath());
                                                                        return;
                                                                    }
                                                                }
                                                                showMessage(Objects.requireNonNull(error.getMessage()));

                                                            }));
                                                }
                                            }

                                            @Override
                                            public void onCancel() {

                                            }
                                        });
                                break;
                        }
                    } else if (permission.shouldShowRequestPermissionRationale) {
                        // 用户拒绝了该权限，没有选中『不再询问』（Never ask again）,那么下次再次启动时，还会提示请求权限的对话框
                        showMessage("权限未获取");

                    } else {
                        // 用户拒绝了该权限，并且选中『不再询问』
                        showMessage("权限未获取");
                    }
                });

        subscribe(disposable);
    }

    @SuppressLint("CheckResult")
    void requestAudioPermissions() {
        RxPermissions rxPermission = new RxPermissions(getActivity());
        Disposable disposable = rxPermission
                .requestEach(
                        Manifest.permission.RECORD_AUDIO
                )
                .subscribe(permission -> {
                    if (permission.granted) {
                        // 用户已经同意该权限
                        audioRecoderUtils = new AudioRecoderUtils();
                        audioRecoderUtils.setOnAudioStatusUpdateListener(new AudioRecoderUtils.OnAudioStatusUpdateListener() {
                            @Override
                            public void onUpdate(double db, long time) {
                                Log.i("audiorecord", "录音中");
                            }

                            @Override
                            public void onStop(String filePath) {
                                audioPath = filePath;
                                try {
                                    tvRecord.setText(AudioUtils.getAmrDuration(new File(filePath)) + "\"");
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                                uploadAdapter.setHaveAudio(true);
                                //initQiNiuUtil();
                                //qiNiuUtil.uploadeAudio(audioRecoderUtils.getFilePath(), qiNiuToken);
                                uploadType = 2;
                                UploadUtils.getInstance().upload(audioRecoderUtils.getFilePath(), qiNiuToken,
                                        UploadUtils.AUDIO, onUploadListener);
                                showLoading();
                                Log.i("audiorecord", "录音结束");
                            }
                        });
                        Log.i("audiorecord", "开始录音");
                        audioRecoderUtils.startRecord();
                        showRecordPop();
                    } else if (permission.shouldShowRequestPermissionRationale) {
                        // 用户拒绝了该权限，没有选中『不再询问』（Never ask again）,那么下次再次启动时，还会提示请求权限的对话框
                    } else {
                        // 用户拒绝了该权限，并且选中『不再询问』
                    }
                });
        subscribe(disposable);
    }

    private int uploadType = 0;

    private OnUploadListener onUploadListener = new OnUploadListener() {
        @Override
        public void onUploadImage(UploadBean result) {
            if (uploadType == 1) {
                coverUrl = result.getNormalUrl();
                commit();
            } else if (uploadType == 2) {
                tvRecord.setVisibility(View.VISIBLE);
                ivRecordDelete.setVisibility(View.VISIBLE);
                audioUrl = result.getNormalUrl();
            } else if (uploadType == 3) {
                videoUrl = result.getNormalUrl();

            }
            hideLoading();
        }

        @Override
        public void onUploadImages(List<UploadBean> results) {
            for (UploadBean bean : results) {
                imgs.add(bean.getNormalUrl());
            }
            hideLoading();
        }

        @Override
        public void onError(int errCode, String errMsg) {
            LogUtils.e("errCode:" + errCode + "\nerrMsg:" + errMsg);
            hideLoading();
        }
    };

    private void uploadImage(List<String> filePaths) {
        urls.clear();
        urls.addAll(filePaths);
        uploadAdapter.addData(urls);
        //initQiNiuUtil();
        //qiNiuUtil.uploadImagesToQiniu(urls, qiNiuToken);
        uploadType = 0;
        UploadUtils.getInstance().uploadImages(urls, qiNiuToken, onUploadListener);
        showLoading();
    }

    private void uploadVideo(String filePath) {
        /*Uri uri = data.getData();
        // 视频路径
        final String videoPath = FileUtil.getPath(getActivity(), uri);*/
        this.videoPath = filePath;
        // 视频大小
        long videoSize = 0;
        try {
            videoSize = FileUtil.getFileSize(new File(videoPath));
        } catch (Exception e) {
            e.printStackTrace();
        }
//            showLog("videoPath== " + videoPath + " videoSize== " + videoSize);
        //转换文件大小类型
        if (videoSize > MAX_LENGTH) {
            showMessage("大小超出限制，最大20MB");
            return;
        }
        MediaMetadataRetriever mmr = new MediaMetadataRetriever();
        mmr.setDataSource(new File(videoPath).getAbsolutePath());
        // 通过视频路径获取bitmap
        Bitmap bitmap = mmr.getFrameAtTime();
        //把bitmap保存到sdcard然后得到图片的路径
        String imagePath = FileUtil.saveBitmapToSDCard(bitmap, System.currentTimeMillis() + ".jpg");
        //显示到控件上
        coverUrl = imagePath;
        uploadAdapter.setVideoUrl(imagePath);
        //qiNiuUtil.uploadeVideo(videoPath, qiNiuToken);
        uploadType = 3;
        UploadUtils.getInstance().upload(filePath, qiNiuToken, UploadUtils.VIDEO, onUploadListener);
        showLoading();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) return;
        if (requestCode == REQUEST_CODE_CHOOSE_HOUSE) {
            tvHouse.setText(data.getStringExtra("EXTRA_KEY_HOUSE_NAME"));
            houseId = data.getIntExtra("EXTRA_KEY_HOUSE_ID", 0);
        }
    }

    private void showRecordPop() {
        CustomPopupWindow customPopupWindow = new CustomPopupWindow.Builder(getActivity())
                .setAnimationStyle(R.anim.pop_enter_anim)
                .setFouse(true)
                .setOutSideCancel(false)
                .setwidth(ViewGroup.LayoutParams.MATCH_PARENT)
                .setheight(ViewGroup.LayoutParams.MATCH_PARENT)
                .setContentView(R.layout.pop_audio_record)
                .builder();
        ViewGroup rlRoot = (ViewGroup) customPopupWindow.getItemView(R.id.rl_root);
        rlRoot.setOnClickListener(view -> {
            if (audioRecoderUtils != null) {
                audioRecoderUtils.stopRecord();
                customPopupWindow.dismiss();
            }
        });
        customPopupWindow.showCenter(R.layout.fragment_complain);
    }

    private void initRecordTimer() {
        recordTimer = new Timer();
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(() -> {
                    Message msg = Message.obtain();
                    msg.what = 1;
                    msg.obj = "showAudioAnim";
                    mHandler.sendMessage(msg);
                });
            }
        };
        recordTimer.schedule(timerTask, 0, 500);
    }

    private void initPlayer(String filePath) {
        initRecordTimer();
        try {
            mediaPlayer = new MediaPlayer();
            mediaPlayer.setOnCompletionListener(mediaPlayer -> {
                if (recordTimer != null) {
                    recordTimer.cancel();
                }
            });
            try {
                mediaPlayer.setDataSource(filePath);
                if (!mediaPlayer.isPlaying()) {
                    mediaPlayer.prepare();
                    mediaPlayer.start();
                }
            } catch (IOException e) {
                mediaPlayer = null;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onDestroyView() {
        if (recordTimer != null) {
            recordTimer.cancel();
        }
        super.onDestroyView();
    }

    @Override
    public void onFetchRepairsList(List<RepairsResult> results) {

    }

    @Override
    public void onGetQiNiuToken(String token) {
        qiNiuToken = token;
    }

    @Override
    public void onTaskSuccess(int taskId) {
        super.onTaskSuccess(taskId);
        if (taskId == RepairsPresenter.COMMIT) {
            if (getActivity() != null) {
                getActivity().finish();
            }
        }
    }

    class mHandle extends Handler {
        @Override
        public void handleMessage(@NonNull Message msg) {
            if (msg.what == 1) {
                if (tvRecord != null) {
                    tvRecord.getBackground().setLevel(tvRecord.getBackground().getLevel() == 2 ? 1 : 2);
                }
            }
        }
    }
}
